<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of user
 *
 * @author Leonardo Lino
 */
require_once 'gestorDatabase.php';

class user extends gestorDatabase {

    private $characters = array(
        "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M",
        "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
        "1", "2", "3", "4", "5", "6", "7", "8", "9");

    function __construct() {
        parent::__construct();
    }

    public function listUsers() {
        $query = $this->db->query('SELECT * FROM utilizadores_tbl');

        if ($query->result_array() != null) {
            return $query->result_array();
        }
        return null;
    }

    public function getAdmins() {
        $sql = 'SELECT *  FROM utilizadores_tbl where tipo=2';
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    public function getUserByID($uid) {
        $query = $this->db->query("SELECT * FROM utilizadores_tbl where id='$uid' ");
        $row = $query->row();
        $ok = ($row != null) ? $row : null;
        return $ok;
    }

    public function isAdmin() {
        $res = $this->session->all_userdata();
        if (isset($res['login']) && $res['tipo'] > 1) {
            return true;
        } else {
            return false;
        }
    }

    public function isValidUser() {
        $res = $this->session->all_userdata();
        if (isset($res['login']) && $res['login'] == "ok") {
            return $this->isValidatedEquipa($res['uid'], $res['tipo']);
        } else {
            return false;
        }
    }
    
    private function isValidatedEquipa($uid, $type){
        $CI =& get_instance();
        $CI->load->model('equipaModel','equipaModel',true);
        
        if ($type==1){
       $equipa =  $CI->equipaModel->getEquipaFromUid($uid);
       if ($equipa->ativo==1){
           return true;
       } else {
           return false;
       }
        } else {
            return true;
        }
    }

    public function isAccessBackOffice($smarty) {
        if (!$this->isAdmin($smarty)) {
            $this->notAdmin($smarty);
        }
    }

    public function notAdmin($smarty) {
        $smarty->display('header.tpl.html');
        $smarty->assign("isAdmin", 0);
        $smarty->display('login.tpl.html');
        $smarty->display('footer.tpl.html');
        exit();
    }

    public function doLogin($user, $password) {

        $pHash = hash('sha512', $password);

        $sql = 'SELECT * FROM utilizadores_tbl where utilizador=?';

        $query = $this->db->query($sql, array($user));
        $row = $query->row();
        if ($row == null) {
            return false;
        }

        $pHashDB = $row->password;

        if ($this->receitaSecreta($pHash, $row->salt) == $this->receitaSecreta($row->password, $row->salt)) {
            $res = array('utilizador' => $row->utilizador, 'uid' => $row->id, 'uid' => $row->id, 'login' => 'ok', 'tipo' => $row->tipo);
            return $res;
        } else {
            return false;
        }
    }

    private function receitaSecreta($passHash, $salt) {
        return $passHash . $salt;
    }

    public function createUser($utilizador, $password, $tipo) {
        $pHash = hash('sha512', $password);

        if ($tipo == 1 || $tipo == 2) {
            $sql = "INSERT INTO `utilizadores_tbl` (utilizador, password, salt, tipo) VALUES (?,?,?,?)";

            $query = $this->db->query($sql, array($utilizador, $pHash, $this->randomSalt(), $tipo));

            if ($tipo == 2) {
                $last_id = $this->db->insert_id();
                $sql = "INSERT INTO `administradores_tbl` (`uid`) VALUES ('$last_id')";
                $this->db->query($sql);
            }
        }
    }

    private function randomSalt() {

        //O tamanho do salt vai ser um aleatorio entre 6 e 10
        $count = rand(6, 10);

        $random_chars = '';
        
        $i= 0;
        while ($i < $count) {
            $x = mt_rand(0, count($this->characters) - 1);
            $random_chars .= $this->characters[$x];
            $i++;
        }

        
        return $random_chars;
    }

    public function getSalt() {
        return $this->salt;
    }

}

?>